package dbs

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"time"
)

type DbUser struct {
	ID             uint      `json:"id" gorm:"primary_key"`                                //
	Name           string    `json:"name" gorm:"type:varchar(64);not null"`                // 姓名
	Gender         string    `json:"gender" gorm:"type:varchar(16);not null"`              // 性别
	Phone          string    `json:"phone" gorm:"type:varchar(32);not null"`               // 手机号
	Role           string    `json:"role" gorm:"type:varchar(16);not null"`                // 角色：超管 管理员、职工  患陪
	Status         string    `json:"status" gorm:"type:varchar(16);not null"`              // 状态：启用、冻结
	Password       string    `json:"password" gorm:"type:varchar(32);not null"`            // 登录密码
	Department     string    `json:"department" gorm:"type:varchar(64)"`                   // 科室
	OpenID         string    `json:"open_id" gorm:"type:varchar(64)"`                      // 微信 openiD
	Identity       string    `json:"identity" gorm:"type:varchar(64);not null;default:''"` // 身份
	EditedPassword bool      `json:"edited_password" gorm:"type:bool;default:false"`       // 初次登录修改密码
	CreatedBy      string    `json:"created_by" gorm:"type:varchar(64)"`                   // 创建人
	LastLoginAt    string    `json:"last_login_at" gorm:"type:varchar(32);not null;default:''"`
	CreatedAt      time.Time `json:"created_at" gorm:"type:datetime"`
	UpdatedAt      time.Time `json:"updated_at" gorm:"type:datetime"`
	TmeshId        string    `json:"tmesh_id"   gorm:"type:varchar(225);not null;default:''"` //
	Vip            int       `json:"vip"`                                                     //超管标识 1 为超管
	//Inpatient	   string 	 `json:"inpatient"` //病区
	//InpatientId	   int 		 `json:"inpatient_id"` //病区id
}

type S_User_Login struct {
	Phone    string `json:"phone" validate:"required" label:"手机号"`
	Password string `json:"password" validate:"required" label:"密码"`
	T        string `json:"t" validate:"required" label:"时间戳秘钥"`
	Identity string `json:"identity"` // 身份
}

type S_User_Login_H5 struct {
	Phone    string `json:"phone" `
	Password string `json:"password" `
	T        string `json:"t" `
	Role     string `json:"role" label:"登录角色"`
	Identity string `json:"identity"` // 身份
}

type S_User_H5Register_H5 struct {
	Name       string `json:"name"`
	Gender     string `json:"gender"`
	Phone      string `json:"phone" validate:"required,isUserPhone" label:"手机号"`
	Password   string `json:"password"  validate:"required" label:"密码"`
	T          string `json:"t" `
	Role       string `json:"role"`        // 角色：超管 管理员、职工  患陪
	Department string `json:"department" ` // 科室
	Identity   string `json:"identity"`    // 身份
	Captcha    string `json:"captcha"`     // 验证码
	CaptchaId  string `json:"captchaId"`   // 验证码ID
}

// 验证姓名、手机号、身份证 格式正确
// 姓名：/^[\u4E00-\u9FA5]{2,5}$/
// 手机号：/^1[3456789]\d{9}$/
type S_User_Create struct {
	Name       string `json:"name" validate:"required,isUserName" label:"真实姓名"`
	Gender     string `json:"gender" validate:"required,max=16" label:"性别"`
	Phone      string `json:"phone" validate:"required,isUserPhone" label:"手机号"`
	Department string `json:"department" label:"科室"`
	Identity   string `json:"identity"` // 身份
	Role       string `json:"role" lable:"角色"`
	Founder    string `json:"founder" lable:"创建人"`
	Inpatient  string `json:"inpatient" label:"病区"`
}

type S_User_Update struct {
	ID         uint   `json:"id" validate:"required"`
	Name       string `json:"name" validate:"omitempty,isUserName" label:"真实姓名"`
	Gender     string `json:"gender"  validate:"omitempty,max=16" label:"性别"`
	Phone      string `json:"phone" validate:"omitempty,isUserPhone" label:"手机号"`
	Role       string `json:"role"`
	Status     string `json:"status"`
	Department string `json:"department"`
	Inpatient  string `json:"inpatient" label:"病区"`
}

type S_User_List struct {
	Name        string `json:"name" `
	Phone       string `json:"phone" `
	Department  string `json:"department"`
	Gender      string `json:"gender"`
	LastLogin   string `json:"lastLogin"`
	CreateAdmin string `json:"createAdmin"`
	CreatedAt   string `json:"created_at"`
	Role        string `json:"role"`
	Identity    string `json:"identity"` // 身份
	Status      string `json:"status"`
	Page        int    `json:"page" label:"页数"`
	Limit       int    `json:"limit" label:"每页显示数"`
	Order       string `json:"order" `
	InterUserId uint
	InterRole   string
}

type S_User_Get struct {
	ID       uint   `json:"id" `
	Name     string `json:"name" `
	Phone    string `json:"phone" `
	Identity string `json:"identity"`
}

type S_User_Exist struct {
	No        string `json:"no"`
	JobNumber string `json:"job_number"`
	Phone     string `json:"phone"`
	Role      string `json:"role"`
}

type S_User_EditPassword struct {
	OldPassword string `json:"old_password"`
	NewPassword string `json:"new_password" validate:"required" label:"新密码"`
}

type S_User_ResetPassword struct {
	ID uint `json:"id" validate:"required"`
}

type S_User_Registe struct {
	Name     string `json:"name" validate:"required,max=64" label:"真实姓名"`
	Gender   string `json:"gender" validate:"required,max=16" label:"性别"`
	IDNumber string `json:"id_number" validate:"required,max=32" label:"身份证号"`
	Phone    string `json:"phone" validate:"required,max=32" label:"手机号"`
	Image    string `json:"image" `
	Company  string `json:"company" validate:"max=32" label:"公司"`
	Position string `json:"position" validate:"max=32" label:"职位"`
}

type S_User_Static struct {
	Name string `json:"name" `
	Role string `json:"role" `
}

func (self *DbUser) Exist() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		if self.Phone != "" {
			conn = conn.Where("(phone = ?)", self.Phone)
		}

		if self.OpenID != "" {
			conn = conn.Where("open_id = ?", self.OpenID)
		}

		if self.Role == "访客" {
			conn = conn.Where("role = ?", self.Role)
		}
		if self.Role != "" && self.Role != "访客" {
			conn = conn.Where("role <> ?", "访客")
		}

		if self.ID != 0 {
			conn = conn.Where("id <> ? ", self.ID)
		}

		return conn.Find(&self).Error
	})
	return
}

func (self *DbUser) Query(s_list S_User_List) (result []DbUser, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if s_list.Name != "" {
			conn = conn.Where("name like ?", s_list.Name)
		}

		if s_list.Phone != "" {
			conn = conn.Where("phone like ?", s_list.Phone)
		}

		if s_list.Status != "" {
			conn = conn.Where("status = ?", s_list.Status)
		}

		if s_list.Department != "" {
			conn = conn.Where("department = ?", s_list.Department)
		}

		if s_list.Identity != "" {
			switch s_list.Identity {
			case "职工":
				if s_list.InterRole == "超级管理员" {
					conn = conn.Where("role IN (?)", []string{"超级管理员", "管理员", "职工"})
				} else {
					if s_list.InterUserId > 0 {
						conn = conn.Where("role = ? or id = ?", "职工", s_list.InterUserId)
					} else {
						conn = conn.Where("role = ? ", "职工")
					}
				}
			case "患陪":
				conn = conn.Where("role IN (?) ", []string{
					"患陪", "患者",
				})
			default:
				conn = conn.Where("role = ?", s_list.Role)
			}
		} else {
			if s_list.InterRole != "超级管理员" {
				if s_list.InterUserId > 0 {
					conn = conn.Where("role Not IN (?) or id = ?", []string{
						"超级管理员", "管理员",
					}, s_list.InterUserId)
				} else {
					conn = conn.Where("role Not IN (?)", []string{
						"超级管理员", "管理员",
					})
				}
			}
		}

		if s_list.Role != "" {
			conn = conn.Where("role = ?", s_list.Role)
		}

		// 分页
		if s_list.Page != 0 && s_list.Limit != 0 {
			conn = conn.Offset((s_list.Page - 1) * s_list.Limit).Limit(s_list.Limit)
		}

		if s_list.Order != "" {
			conn = conn.Order(s_list.Order)
		} else {
			conn = conn.Order("id DESC")
		}

		return conn.Find(&result).Error
	})
	return
}

func (self *DbUser) Count(s_list S_User_List) (count int, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		fmt.Println(s_list)
		if s_list.Name != "" {
			conn = conn.Where("name like ?", s_list.Name)
		}
		conn = conn.Where("role = ?", "患陪")
		return conn.Model(&self).Count(&count).Error
	})
	return
}

func (self *DbUser) CountList(s_list S_User_List) (count int, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if s_list.Name != "" {
			conn = conn.Where("name like ?", s_list.Name)
		}

		if s_list.Phone != "" {
			conn = conn.Where("phone like ?", s_list.Phone)
		}

		if s_list.Status != "" {
			conn = conn.Where("status = ?", s_list.Status)
		}

		if s_list.Department != "" {
			conn = conn.Where("department = ?", s_list.Department)
		}

		if s_list.Role != "" {
			conn = conn.Where("role = ?", s_list.Role)
		}

		if s_list.Identity != "" {
			switch s_list.Identity {
			case "职工":
				if s_list.InterRole == "超级管理员" {
					conn = conn.Where("role IN (?)", []string{
						"超级管理员", "管理员", "职工",
					})
				} else {
					if s_list.InterUserId > 0 {
						conn = conn.Where("role = ? or id = ?", "职工", s_list.InterUserId)
					} else {
						conn = conn.Where("role = ? ", "职工")
					}
				}
			case "患陪":
				conn = conn.Where("role IN (?) ", []string{
					"患陪", "患者",
				})
			default:
				conn = conn.Where("role = ?", s_list.Role)
			}
		} else {
			if s_list.InterRole != "超级管理员" {
				if s_list.InterUserId > 0 {
					conn = conn.Where("role Not IN (?) or id = ?", []string{
						"超级管理员", "管理员",
					}, s_list.InterUserId)
				} else {
					conn = conn.Where("role Not IN (?)", []string{
						"超级管理员", "管理员",
					})
				}
			}
		}

		return conn.Model(&self).Count(&count).Error
	})
	return
}

func (self *DbUser) Get() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if self.ID > 0 {
			conn = conn.Where("id = ?", self.ID)
			self.ID = 0
		}
		if self.Department != "" {
			conn = conn.Where("department = ?", self.Department)
		}
		if self.Name != "" {
			conn = conn.Where("name = ?", self.Name)
		}
		if self.Phone != "" {
			conn = conn.Where("phone = ?", self.Phone)
		}

		return conn.Find(&self).Error
	})
	fmt.Println("result :", self)
	return
}

func (self *DbUser) GetById() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		conn = conn.Where("id = ?", self.ID)

		return conn.First(&self).Error
	})
	return
}

func (self *DbUser) Create() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		return conn.Create(&self).Error
	})
	return
}

func (self *DbUser) Update(params map[string]interface{}) (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		return conn.Model(&self).Update(params).Error
	})
	return
}

func (self *DbUser) UpdateRaw(db *gorm.DB, params map[string]interface{}) (err error) {

	return db.Model(&self).Update(params).Error
}
